package com.ustadzmenjawab.indexing;

import java.io.StringReader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import org.apache.lucene.analysis.id.IndonesianAnalyzer;
import org.apache.lucene.analysis.synonym.SolrSynonymParser;
import org.apache.lucene.analysis.synonym.SynonymMap;
import org.apache.lucene.util.Version;

import com.ustadzmenjawab.server.DBConnFactory;

public class UstadzMenjawabSynonymMap {
	private static SynonymMap synonymMap;
	static{
		buildSynonymMap();
	}
	public static SynonymMap getInstance(){
		if(synonymMap == null){
			buildSynonymMap();
		}
		return synonymMap;
	}
	
	public static void buildSynonymMap(){
		Connection conn = DBConnFactory.getConnection();
		Statement stmt = null;
		ResultSet rs = null;
		try{
			String sql = "SELECT  term,daftar_sinonim FROM sinonim";
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			SolrSynonymParser solrParser = new SolrSynonymParser(true,true,new IndonesianAnalyzer(Version.LUCENE_35));
			while(rs.next()){
				String term = rs.getString(1);
				String synonymLs = rs.getString(2).replace(";",",");
				String solrFormat = term +" => "+synonymLs;
				StringReader reader = new StringReader(solrFormat);
				try{
					solrParser.add(reader);
				}catch(Exception e){
					System.err.println(solrFormat + " is not succesful to be inserted as synonym.");
					e.printStackTrace();
				}
			}
			synonymMap = solrParser.build();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
